#include "bst_tree.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN_MAX 512

char buffer[LEN_MAX];

// action 函数
bool printStr(void *str) { return printf("%s", (char *)str) >= 0; }

int main() {
  btree tree = bst_create((cmp_func_t *)strcmp, NULL);

  // 修改成你自己的路径
  FILE *fp = fopen("D:/git/c-general-data-structure/tree/bst_tree/text", "r");

  if (fp == NULL) {
    fprintf(stderr, "error open file \n");
    exit(EXIT_FAILURE);
  }

  while (fgets(buffer, LEN_MAX, fp) != NULL) { // 读取每一行
    size_t len = strlen(buffer);
    if (!bst_insert(tree, buffer, len + 1)) // 将文本数据复制到树结构中
      break;
  }

  if (!feof(fp)) {
    fprintf(stderr, "sortlines: Error reading or storing text input.\n");
    exit(EXIT_FAILURE);
  }

  int n = bst_in_order(tree, printStr); // LNR输出, 也就是按字符排序
  fprintf(stderr, "\nsortlines: Printed %d lines.\n", n);
  bst_clear(tree);

  fclose(fp);
  return 0;
}